package com.wb.mas.utils;

import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;

import com.wb.mas.entity.MyContacts;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

/**
 * Copyright (C) 2018,
 * ContactUtils
 * <p>
 * Description
 * 获取通讯录工具类
 *
 * @author yue
 * @version 1.0
 * <p>
 * Ver 1.0, 2019-05-06, yue, Create file
 */
public class ContactUtils {

    /**
     * 将文件存到某个文件中
     *
     * @param context
     * @param path
     * @return
     */
    public static boolean saveAllContacts(Context context, String path) {
        ArrayList<MyContacts> contacts = new ArrayList<MyContacts>();

        Cursor cursor = context.getContentResolver().query(
                ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        FileWriter fw = null;
        BufferedWriter bw = null;
        try {
            fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            while (cursor.moveToNext()) {
                String contactId = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                //获取联系人姓名
                String name = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                //获取联系人电话号码
                Cursor phoneCursor = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
                String sphone = "";
                while (phoneCursor.moveToNext()) {
                    String phone = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    phone = phone.replace("-", "");
                    phone = phone.replace(" ", "");
                    sphone = phone;
                }
                bw.write(sphone + "[(-_-)]" + name+"\n");
                phoneCursor.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        cursor.close();

        return true;

    }
}
